package api

import (
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
	"monthly-test/global"
	"monthly-test/internal/model/dao"
	"monthly-test/internal/model/service"
	"monthly-test/internal/request"
	"monthly-test/internal/response"
	"net/http"
	"strconv"
)

// 短视频列表
func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	list, err := service.List(page, pageSize)
	if err != nil {
		return
	}
	var slice []response.VideoResponse
	for _, video := range list {
		videoResponse := response.VideoResponse{
			UserId: video.UserId,
			Url:    video.Url,
			Likes:  video.Likes,
			Looks:  video.Looks,
		}
		slice = append(slice, videoResponse)
	}
	c.JSON(http.StatusOK, gin.H{"data": slice})

}

// 视频展示
func VideoShow(c *gin.Context) {
	url := c.Query("url")
	var video dao.Video
	err := global.DB.Where("url = ?", url).First(&video).Error
	if err != nil {
		return
	}
	global.Rdb.IncrBy("count", 1)
	c.JSON(http.StatusOK, gin.H{"message": "视频展示成功", "url": url})
}

// 视频点赞
func Likes(c *gin.Context) {

	var req request.VideoReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
		return
	}
	video := dao.Video{
		UserId: req.UserId,
		Likes:  req.Likes,
	}
	err = global.DB.Create(&video).Error
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "点赞成功"})

	global.Rdb.ZAdd("likes", redis.Z{
		Score:  float64(req.Likes),
		Member: req.UserId,
	})
}

// 视频列表
func LikesList(c *gin.Context) {

	result, err := global.Rdb.ZRevRangeWithScores("likes", 0, 10).Result()
	if err != nil {
		return
	}
	var slice []response.VideoReq
	for _, z := range result {
		videoResponse := response.VideoReq{
			UserId: z.Member.(string),
			Likes:  int(z.Score),
		}
		slice = append(slice, videoResponse)
	}
	c.JSON(http.StatusOK, gin.H{"message": "排行榜展示成功", "data": slice})
}
func DelLikes(c *gin.Context) {

	url := c.Query("url")
	var video dao.Video
	err := global.DB.Debug().Where("url = ?", url).Delete(&video).Error
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "取消点赞"})
}
func VideoList(c *gin.Context) {
	var video []dao.Video
	err := global.DB.Find(&video).Error
	if err != nil {
		return
	}
	var req []response.VideoResponse
	for _, d := range video {
		req = append(req, response.VideoResponse{
			UserId: d.UserId,
			Url:    d.Url,
			Likes:  d.Likes,
			Looks:  d.Looks,
		})
	}
	c.JSON(http.StatusOK, gin.H{"message": "成功", "data": req})
}
